import { SIGNATURE } from "./config.js";
// import { Md5 } from "ts-md5";
import md5 from "js-md5";
import Base64 from 'base-64'

export function stringToBase64(str) {
  return Base64.encode(str);
}

export function base64ToString(str) {
  return Base64.decode(str);
}

export function paramSignature(params) {
  if (!isObject(params)) {
    return params;
  }
  let str = "";
  let keys = Object.keys(params).sort((a, b) => {
    if (a.toLowerCase() < b.toLowerCase()) {
      return -1;
    }
    if (a.toLowerCase() > b.toLowerCase()) {
      return 1;
    }
    return 0;
  });
  keys.map((key) => {
    str += params[key];
  });
  // const md5 = new Md5()
  // let md5String = md5.appendAsciiStr(md5.appendAsciiStr(str) + SIGNATURE).end();
  let md5String = md5(md5(str) + SIGNATURE);
  return md5String;
}

const obj = {
  jents: "http://google.com.cn,baidu.com",
  gdensd: "http://google.com.cn",
  alert: "alert的值",
  fire: "is fire",
  Bojs: "name",
};

paramSignature(obj);

export function encryptByXOR(message, key = SIGNATURE) {
  var encrypted = "";
  // else if(/[0-9]/.test(message)){
  //   return stringToBase64(message);
  // }
  if(!message){
    return encrypted
  }else if (message) {
    for (var i = 0; i < message.length; i++) {
      var c = message.charCodeAt(i) ^ key.charCodeAt(i % key.length);
      encrypted += String.fromCharCode(c);
    }
  }
  // console.log("encryptByXOR:",encrypted);
  if(encrypted){
    encrypted = stringToBase64(encrypted);
  }
  return encrypted;
}

export function isObject(target) {
  if (typeof target === "object" && target !== null && !Array.isArray(target)) {
    return true;
  } else {
    return false;
  }
}
